package net.tngou.jtdb.netty;


import java.io.File;
import java.io.IOException;




import org.apache.commons.configuration2.PropertiesConfiguration;
import org.apache.commons.configuration2.builder.fluent.Configurations;
import org.apache.commons.configuration2.ex.ConfigurationException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import net.tngou.db.util.ResultSet;
import net.tngou.db.util.SerializationUtils;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;


public class TngouClient {

	 
//	 static Response set =new Response();
	private static Log log = LogFactory.getLog(TngouClient.class);
	private   Channel channel=null;
	private   ClientHandler clh=new ClientHandler();
	private   EventLoopGroup group = new NioEventLoopGroup();
	private static String HOST = "127.0.0.1";
	private  static  int PORT = 8827;
	 
	public TngouClient()
	 {
		 
		 Bootstrap boot = new Bootstrap();
		 
		 boot.group(group)
		 .channel(NioSocketChannel.class)
		  .option(ChannelOption.TCP_NODELAY, true)
		  .handler(new ChannelInitializer<SocketChannel>() {
			  
			  @Override
			  public void initChannel(SocketChannel ch) throws Exception {
				ChannelPipeline pipeline = ch.pipeline();

			  	pipeline.addLast(new ObjectEncoder());
			  	pipeline.addLast(new ObjectDecoder(ClassResolvers.cacheDisabled(null)));
			  	pipeline.addLast(clh);
			  	
			  	}

			
		  });
		  
		
		 try {
			 
			
			    Configurations configs = new Configurations();
				File ynhouFile = new File("tngou.properties");
				PropertiesConfiguration config = configs.properties(ynhouFile);
				 HOST = config.getString("host");
				 PORT = config.getInt("port");
			    channel = boot.connect(HOST, PORT).sync().channel();
			    log.debug("建立服务器连接-"+HOST+":"+PORT);
			   
		} catch (InterruptedException | ConfigurationException e) {
			log.error("连接服务器-"+HOST+":"+PORT+" 失败");
			e.printStackTrace();
		}
	 }
	 
	 
	 
	 public ResultSet exe(String sql) throws IOException, InterruptedException {
		 ChannelFuture cf = null;
		 ResultSet res= new ResultSet();
		 res.setMsg(sql);
		 byte[] bytes = SerializationUtils.serialize(res);
		 
		 cf = channel.writeAndFlush(bytes);
		 cf.sync();
		 ResultSet response =null;
//		 Thread.sleep(20);
		 response=clh.getResponse();
		 while (response==null) {
			 Thread.sleep(1);
			 response=clh.getResponse();
			
		}
			
		clh.clearResponse();
//		 channel.closeFuture().sync();
//		if(sql.startsWith("exit"))
		
			 
		return response;
	}
	 
	 
	 
	 /**
	  * 关闭连接
	 * @Title: close
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @param     设定文件
	 * @return void    返回类型
	 * @throws
	  */
	 public void close() {
		 group.shutdownGracefully();
		 log.debug("关闭连接");
	}
	 
	 


 
 
 
	
}
